package com.taptech.doufu.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.taptech.doufu.weex.http.TFCookieUtil;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.net.httputils.DiaobaoCookieStore;

public class HttpRequestUtil
{

    private final static int CONNECTION_TIMEOUT = 5 * 1000;
    private final static int SO_TIMEOUT = 15 * 1000;
    private static HttpContext context = new BasicHttpContext();
    private static final String COOKIE = "cookie";

    public static HttpContext getContext() {
        return context;
    }

    public static List<String> requests = new ArrayList<String>();

    public HttpRequestUtil()
    {
    }

    public static JSONObject getJsonObjectFromServer(String link,int conn_timeout,int so_timeout){
        link = Constant.changeUrlHost(link);
        if (context.getAttribute(ClientContext.COOKIE_STORE) == null)
        {
            context.setAttribute(ClientContext.COOKIE_STORE, new DiaobaoCookieStore());
        }

        if (AccountService.getInstance().isLogin())
        {
            initCookie();
        }

        if (requests.contains(link))
        {
            TTLog.s("repeat request URL::::::" + link);
            return null;
        }
        requests.add(link);

        TTLog.e("getJsonObjectFromServer", link);
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, conn_timeout * 2);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, so_timeout);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        StringBuilder builder = new StringBuilder();
        try
        {
            HttpGet myget = new HttpGet(link);
            AndroidHttpClient.modifyRequestToAcceptGzipResponse(myget);
            if (link.contains("user_login") || link.contains("phone_register2_1") || link.contains("registerWithEmail"))
            {
                if (!AccountService.getInstance().isLogin())
                {
                    DiaobaoCookieStore localCookies = new DiaobaoCookieStore();
                    context.setAttribute(ClientContext.COOKIE_STORE, localCookies);
                }
            }

            DiaobaoCookieStore cookies = TFCookieUtil.getCookies();
            context.setAttribute(ClientContext.COOKIE_STORE, cookies);
            HttpResponse response = client.execute(myget, context);
            BufferedReader reader = new BufferedReader(new InputStreamReader(AndroidHttpClient.getUngzippedContent(response.getEntity())));

            for (String s = reader.readLine(); s != null; s = reader.readLine())
            {
                builder.append(s);
            }
            requests.remove(link);
            jsonObject = new JSONObject(builder.toString());
            if (link.contains("user_login") || link.contains("phone_register2_1") || link.contains("registerWithEmail"))
            {
                if (!AccountService.getInstance().isLogin())
                {

                    BasicCookieStore store = (BasicCookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
                    if (store != null)
                    {
                        HashMap<String, Object> values = new HashMap<String, Object>();
                        List<Cookie> respCookieList = store.getCookies();
                        if (respCookieList != null)
                            for (Cookie ck : respCookieList)
                            {
                                if(!"xx".equals(ck.getName())){
                                    values.put(ck.getName(), ck.getValue());
                                    values.put(Constant.DATE, ck.getExpiryDate());
                                    values.put(Constant.DOMAIN, ck.getDomain());
                                }
                            }
                        if (jsonObject.has("meta"))
                        {
                            if (jsonObject.getJSONObject("meta").has("login"))

                                storeCookie(values, DiaobaoUtil.getStringFromJSONObject(jsonObject.getJSONObject("meta").getJSONObject("login"), Constant.UID));
                        }
                    }
                }
            }
        } catch (Exception e)
        {
            requests.remove(link);
            e.printStackTrace();
        }



        return jsonObject;
    }

    /**
     * special for articles, medias etc with pages
     */
    public static JSONObject getJsonObjectFromServer(String link) {
        return getJsonObjectFromServer(link, CONNECTION_TIMEOUT, SO_TIMEOUT);
    }

    /**
     * special for articles, medias etc with pages
     */
    public static JSONObject postToServer(String link, List<NameValuePair> nameValuePairs)
    {
        link = Constant.changeUrlHost(link);


        if (context.getAttribute(ClientContext.COOKIE_STORE) == null)
        {
            context.setAttribute(ClientContext.COOKIE_STORE, new DiaobaoCookieStore());
        }

        if (AccountService.getInstance().isLogin())
        {
            initCookie();
        }
        if (requests.contains(link))
        {
            TTLog.s("repeat request URL::::::" + link);
            return null;
        }
        requests.add(link);
        JSONObject jsonObject = null;
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT * 2);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT * 4);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        StringBuilder builder = new StringBuilder();
        try
        {
            HttpPost mypost = new HttpPost(link);
            for (NameValuePair nameValuePair : nameValuePairs)
            {
                TTLog.s(nameValuePair.getName() + ":::::" + nameValuePair.getValue());
            }

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            mypost.setEntity(entity);

            if (link.contains("member/wxcodelogin")||
                    link.contains("/index.php/member/social_bind_register") ||
                    link.contains("email_register") ||
                    link.contains("phone_register2_1") ||
                    link.contains("registerWithEmail"))
            {
                if (!AccountService.getInstance().isLogin())
                {
                    DiaobaoCookieStore localCookies = new DiaobaoCookieStore();
                    context.setAttribute(ClientContext.COOKIE_STORE, localCookies);
                }
            }
            DiaobaoCookieStore cookies = TFCookieUtil.getCookies();
            context.setAttribute(ClientContext.COOKIE_STORE, cookies);
            HttpResponse response = client.execute(mypost, context);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            for (String s = reader.readLine(); s != null; s = reader.readLine())
            {
                builder.append(s);
            }
            TTLog.s("base_response:" + builder.toString());
            requests.remove(link);
            jsonObject = new JSONObject(builder.toString());
            if (link.contains("member/wxcodelogin")||
                    link.contains("/index.php/member/social_bind_register") ||
                    link.contains("email_register") ||
                    link.contains("phone_register2_1") ||
                    link.contains("registerWithEmail"))
            {
                if (!AccountService.getInstance().isLogin())
                {
                    BasicCookieStore store = (BasicCookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
                    if (store != null)
                    {
                        HashMap<String, Object> values = new HashMap<String, Object>();
                        List<Cookie> respCookieList = store.getCookies();
                        if (respCookieList != null)
                            for (Cookie ck : respCookieList) {
                                if(!"xx".equals(ck.getName())){
                                    values.put(ck.getName(), ck.getValue());
                                    values.put(Constant.DATE, ck.getExpiryDate());
                                    values.put(Constant.DOMAIN, ck.getDomain());
                                }
                            }
                        if (jsonObject.has(Constant.DATA)) {
                            storeCookie(values, DiaobaoUtil.getStringFromJSONObject(jsonObject.getJSONObject(Constant.DATA), Constant.UID));
                        }

                    }
                }
            }

        } catch (Exception e)
        {
            HttpRequestUtil.requests.remove(link);
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static void storeCookie(HashMap<String, Object> stroe, String uid) {
        String dtString = "2035-12-12";
        stroe.put(Constant.DATE, dtString);
        JSONObject obj = new JSONObject(stroe);
        try
        {
            WeMediaApplication.applicationContext.getSharedPreferences(COOKIE, Context.MODE_PRIVATE).edit().putString(uid, obj.toString(0)).commit();
            TFCookieUtil.setNeedUpdate();//qlx

        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        //		}
    }

    @SuppressWarnings("unchecked")
    public static void initCookie()
    {
        try
        {
            String json = WeMediaApplication.applicationContext.getSharedPreferences(COOKIE, Context.MODE_PRIVATE).getString(AccountService.getInstance().getUserUid(), null);
            JSONObject obj = new JSONObject(json);
            DiaobaoCookieStore store = new DiaobaoCookieStore();
            Iterator<String> it = obj.keys();
            while (it.hasNext())
            {
                String key = (String) it.next();
                if (!key.equals(Constant.DOMAIN) && !key.equals(Constant.DATE))
                {
                    BasicClientCookie cookie = new BasicClientCookie(key, (String) obj.get(key));
                    Date date = DateUtil.strToDate(obj.getString(Constant.DATE));
                    cookie.setExpiryDate(date);
                    cookie.setDomain((String) obj.get(Constant.DOMAIN));
                    store.addCookie(cookie);
                }

            }
            context.setAttribute(ClientContext.COOKIE_STORE, store);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        //		}
    }

    private static boolean syncStarted = false;

    public static void getCookie(Context mContext, String url)
    {
        if (!syncStarted)
        {
            CookieSyncManager.createInstance(mContext);
            CookieSyncManager.getInstance().startSync();
            syncStarted = true;
        }

        CookieManager cookieManager = CookieManager.getInstance();

        cookieManager.setAcceptCookie(true);
        //		cookieManager.removeSessionCookie();//移除

        CookieStore store = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
        if (store == null)
        {
            return;
        }

        StringBuilder sb = new StringBuilder();

        Set<String> set = new HashSet<String>();

        for (Cookie ck : store.getCookies())
        {

            if (!set.add(ck.getName()))
            {
                continue;
            }

            sb.setLength(0);
            sb.append(ck.getName()).append('=').append(ck.getValue())
                    .append("; path=/");
            if (!TextUtils.isEmpty(url) && url.contains("api.doufu.la")) {
                sb.append("; domain=").append("doufu.la");
            }else{
                sb.append("; domain=").append(ck.getDomain());
            }
            if(ck.getName().equals("skey")) {
                sb.append("; httponly ");
            }
            ;
            // " skey=54043689d627a7.34768897; expires=Sun, 27-Aug-2034 09:04:10 GMT; path=/; domain=diaobao.la"
            if (sb != null && cookieManager != null && !TextUtils.isEmpty(url)){
                cookieManager.setCookie(url, sb.toString());
            }
        }
       // TTLog.i("TAG", "cookie=================" + sb.toString());
        CookieSyncManager.getInstance().sync();
    }

    public static void clearCookie()
    {
        context.removeAttribute(ClientContext.COOKIE_STORE);
        if (Constant.exitsSDCard)
        {
            File file = new File(Constant.AppDir.FILE_CACHE_DATA + "/cookie" + AccountService.getInstance().getUserUid());
            if (file.exists())
                file.delete();
        } else
        {
            WeMediaApplication.applicationContext.getSharedPreferences(COOKIE, Context.MODE_PRIVATE).edit().remove(AccountService.getInstance().getUserUid()).commit();
        }

        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(WeMediaApplication.applicationContext);
        cookieSyncManager.startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeExpiredCookie();
        cookieManager.removeSessionCookie();//移除
        CookieSyncManager.getInstance().sync();

    }
}
